package extend

import "strings"

type bufferI interface {
	// ChangeToBuffer 切换到临时缓冲区
	ChangeToBuffer(**strings.Builder)

	// WriteInBuffer 写入临时缓冲区
	WriteInBuffer(string)

	// RecoverFromBuffer 从临时缓冲区恢复
	RecoverFromBuffer(**strings.Builder)
}

type BufferStruct struct {
	Buffer *strings.Builder `name:"临时保存textContext"`
}

func (b *BufferStruct) ChangeToBuffer(textContextP **strings.Builder) {
	// 用临时缓冲区替换目标 strings.Builder
	b.Buffer = &strings.Builder{}
	// 缓冲区的指针指向 textContextP 的指针的指针，即 *strings.Builder
	b.Buffer = *textContextP
	// 创建新的 textContextP
	*textContextP = &strings.Builder{}
}

func (b *BufferStruct) WriteInBuffer(content string) {
	b.Buffer.WriteString(content)
}

func (b *BufferStruct) RecoverFromBuffer(tmpBufferP **strings.Builder) {
	if tmpBufferP != nil && b.Buffer != nil {
		// 将缓冲区指向之前保存的 strings.Builder
		*tmpBufferP = b.Buffer
		// 释放临时缓冲区
		b.Buffer = nil
	}
}
